/*
 * based on jQuery File Upload Plugin JS Example 7.0
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

$(document).ready(function(){
	'use strict';
	
	$('#fileupload').fileupload( {
		//url: host+'/upload/gamerecords',
		maxFileSize: 5000000,
		
		maxNumberOfFiles: 1,
		//autoUpload: true,
		
		acceptFileTypes: /(\.|\/)(csv)$/i,
		
		fileInput: $('input:file'),
		///*
		filesContainer: $('#upload_files_container'),
	    uploadTemplateId: null,
	    downloadTemplateId: null,

	    uploadTemplate: function (o) {
	        var rows = $();
	        $.each(o.files, function (index, file) {
	            var row = $(
            		'<tr class="template-upload fade">' +
	                '<td class="preview"><span class="fade"></span></td>' +
	                '<td class="name"></td>' +
	                '<td class="size"></td>' +
	                /*
					(file.error ? '<td class="error" colspan="2"></td>' :
	                        	'<td><div class="progress">' +
	                            '<div class="bar" style="width:0%;"></div></div></td>' +
	                            '<td class="start"><button>Start</button></td>'
	                ) +
					//*/
	                '<td class="cancel"><button>Cancel</button></td></tr>');
	            row.find('.name').text(file.name);
	            row.find('.size').text(o.formatFileSize(file.size));
	            if (file.error) {
	                row.find('.error').text(
	                    locale.fileupload.errors[file.error] || file.error
	                );
	            }
	            rows = rows.add(row);
	        });
			rows.add();
	        return rows;
	    },
		/*
	    downloadTemplate: function (o) {
			var rows = $();
	        $.each(o.files, function (index, file) {
	            var row = $('<tr class="template-download fade">' +
	                (file.error ? '<td></td><td class="name"></td>' +
                			'<td class="size"></td><td class="error" colspan="2"></td>' :
	                        '<td class="preview"></td>' +
	                        '<td class="name"><a></a></td>' +
                            '<td class="size"></td><td colspan="2"></td>') + 
	                '<td class="delete"><button>Delete</button> ' +
                    '<input type="checkbox" name="delete" value="1"></td></tr>');
	            row.find('.size').text(o.formatFileSize(file.size));
	            if (file.error) {
	                row.find('.name').text(file.name);
	                row.find('.error').text(
	                    //locale.fileupload.errors[file.error] || file.error
	                	file.error
	                );
	            } else {
	                row.find('.name a').text(file.name);
	                if (file.thumbnail_url) {
	                    row.find('.preview').append('<a><img></a>')
	                        .find('img').prop('src', file.thumbnail_url);
	                    row.find('a').prop('rel', 'gallery');
	                }
	                row.find('a').prop('href', file.url);
	                row.find('.delete button')
	                    .attr('data-type', file.delete_type)
	                    .attr('data-url', file.delete_url);
	            }
	            rows = rows.add(row);
	        });
	        return rows;
	    },	
	    //*/
		
		// The add callback is invoked as soon as files are added to the
		// fileupload widget (via file input selection, drag & drop or add
		// API call). See the basic file upload widget for more information:
		added: function (e, data) {
			$("#upload_files_container:last button").click(function(){
				var rows = "#record_set-group .tabular.inline-related tbody tr";
				$(rows).each( function(){
						$("tr td input").attr('value', '');
					});
			});
		},
	});
			
	$('input:file').click( function(){
		$(this).attr("value", "");
	});
	$('input:file').change(function(e){
		var ext = ($('.template-upload .name').html()).split('.').pop().toLowerCase();

		if($.inArray(ext, ["csv"]) == -1)
		{
			alert('Upload CSV');
			return false;
		}
		
		if (e.target.files == undefined)
		{
			alert('Upload CSV');
			return false;
		}
	
		var reader = new FileReader();
		reader.onload = function(e) {
			var rfield = ['number', 'name', 'gender', 'totalRank', 'genderRank', 'records', 'avgspeed'];
			var rfconv = [_conv_num, _conv_str, _conv_str, _conv_num, _conv_num, _conv_time, _conv_time];
			var csvval=e.target.result.split("\n");
			var rc = csvval.length;
			for (var row=0; row<rc; ++row)
			{
				if( row==0 ) continue;
				var colval = csvval[row].split(",");
				var colc = colval.length;
				for( var col=0; col < colc; ++col)
				{
					if( col >= rfield.length )
						break;
						
					var v = colval[col];
					$("#id_record_set-"+(row-1)+"-"+ rfield[col]).attr('value', rfconv[col](v) );
				}
				var rows = "#record_set-group .tabular.inline-related tbody tr";
				django.jQuery(rows).data('addButton').target.click();
			}
		};
		reader.readAsText(e.target.files.item(0));
	});
	
	(function($) {
		var oldFnc = $.fn.formset;
		$.fn.formset.defaults  = oldFnc.defaults ;
		$.fn.formset = function () {
			var ret = oldFnc.apply(this, arguments);
			
			return ret;
		};
	})(django.jQuery);
	
});

function _conv_num(s) {
	if( s == '' || s.length == 0)
		return 0;
	return parseInt(s);
};
function _conv_str(s) {
	return s;
};
function _conv_time(s) {
	time = s.split(/:/);
	return time[0] * 3600 + time[1] * 60 + time[2]*1;
};